import React, { useState, useEffect } from 'react';
import { toast } from '@/lib/toast-with-audio';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
import { cn } from '@/lib/utils';
import { motion } from 'framer-motion';
import { knowledgeApi } from '@/store/knowledge';
import type { Article, GetArticlesParams } from '@/types/knowledge';
import { myArticles, myCollections } from '@/data/knowledgeData';
import Drawer from '@/components/Drawer';

// 使用导入的Article类型，不再需要本地定义

// 文章分类数据（图表数据，保留）
const categoryData = [
  { name: 'DevOps', value: 15, color: '#3b82f6' },
  { name: '架构设计', value: 12, color: '#8b5cf6' },
  { name: '性能优化', value: 8, color: '#10b981' },
  { name: '版本控制', value: 10, color: '#f59e0b' },
  { name: '安全', value: 7, color: '#ef4444' },
  { name: '前端开发', value: 13, color: '#6366f1' },
  { name: '后端开发', value: 16, color: '#ec4899' }
];

// 文章趋势数据（图表数据，保留）
const trendData = [
  { month: '1月', 发布数量: 12, 阅读量: 2500 },
  { month: '2月', 发布数量: 15, 阅读量: 3200 },
  { month: '3月', 发布数量: 10, 阅读量: 2100 },
  { month: '4月', 发布数量: 18, 阅读量: 3800 },
  { month: '5月', 发布数量: 14, 阅读量: 2900 },
  { month: '6月', 发布数量: 16, 阅读量: 3500 }
];

// 标签组件
const Tag: React.FC<{ text: string }> = ({ text }) => {
  return (
    <span className="px-2 py-1 text-xs bg-blue-50 dark:bg-blue-900 text-blue-700 dark:text-blue-300 rounded-full mr-2 mb-2 inline-block">
      {text}
    </span>
  );
};

// 分类标签组件
const CategoryTag: React.FC<{ category: string }> = ({ category }) => {
  const categoryMap: Record<string, { bg: string, text: string }> = {
    '技术文档': { bg: 'bg-blue-100 dark:bg-blue-900', text: 'text-blue-700 dark:text-blue-300' },
    '产品文档': { bg: 'bg-green-100 dark:bg-green-900', text: 'text-green-700 dark:text-green-300' },
    '设计规范': { bg: 'bg-purple-100 dark:bg-purple-900', text: 'text-purple-700 dark:text-purple-300' },
    '操作手册': { bg: 'bg-amber-100 dark:bg-amber-900', text: 'text-amber-700 dark:text-amber-300' },
    'FAQ': { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-700 dark:text-gray-300' },
  };
  
  const style = categoryMap[category] || { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-700 dark:text-gray-300' };
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${style.bg} ${style.text}`}>
      {category}
    </span>
  );
};

// 状态徽章组件
const StatusBadge: React.FC<{ status: string }> = ({ status }) => {
  const statusMap: Record<string, { bg: string, text: string }> = {
    '已发布': { bg: 'bg-green-100 dark:bg-green-900', text: 'text-green-700 dark:text-green-300' },
    '草稿': { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-700 dark:text-gray-300' },
    '审核中': { bg: 'bg-blue-100 dark:bg-blue-900', text: 'text-blue-700 dark:text-blue-300' },
    '已归档': { bg: 'bg-gray-200 dark:bg-gray-600', text: 'text-gray-700 dark:text-gray-300' },
  };
  
  const style = statusMap[status] || { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-700 dark:text-gray-300' };
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${style.bg} ${style.text}`}>
      {status}
    </span>
  );
};

// 用户头像组件
const UserAvatar: React.FC<{ name: string }> = ({ name }) => {
  // 从姓名中提取第一个字符
  const initial = name.charAt(0).toUpperCase();
  
  // 为不同的姓氏生成不同的背景色
  const colors = [
    'bg-blue-100 text-blue-600',
    'bg-green-100 text-green-600',
    'bg-purple-100 text-purple-600',
    'bg-amber-100 text-amber-600',
    'bg-pink-100 text-pink-600',
    'bg-indigo-100 text-indigo-600'
  ];
  
  // 简单的哈希函数来选择颜色
  const hash = name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
  const colorClass = colors[hash % colors.length];
  
  return (
    <div className={`w-7 h-7 rounded-full ${colorClass} flex items-center justify-center text-xs font-medium`}>
      {initial}
    </div>
  );
};

export default function Knowledge() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [selectedArticle, setSelectedArticle] = useState<number | null>(null);
  const [activeTab, setActiveTab] = useState<'square' | 'my'>('square'); // 新增：tab状态管理
  const [myTab, setMyTab] = useState<'articles' | 'collections'>('articles'); // 新增：我的知识库子标签状态
  const [drawerOpen, setDrawerOpen] = useState(false); // 抽屉状态
  
  // 我的文章检索和分页状态
  const [articlesSearch, setArticlesSearch] = useState('');
  const [articlesCurrentPage, setArticlesCurrentPage] = useState(1);
  const articlesPerPage = 5;
  
  // 我的收藏检索和分页状态
  const [collectionsSearch, setCollectionsSearch] = useState('');
  const [collectionsCurrentPage, setCollectionsCurrentPage] = useState(1);
  const collectionsPerPage = 5;
  
  // 从store加载文章数据
  useEffect(() => {
    const loadArticles = async () => {
      try {
        setLoading(true);
        const params: GetArticlesParams = {};
        const response = await knowledgeApi.getArticles(params);
        setArticles(response.data || []);
      } catch (error) {
        console.error('加载文章数据失败:', error);
        toast('加载文章数据失败');
      } finally {
        setLoading(false);
      }
    };
    
    loadArticles();
  }, []);

  // 我的文章检索和分页逻辑
  const filteredMyArticles = myArticles.filter(article => 
    article.title.toLowerCase().includes(articlesSearch.toLowerCase()) ||
    article.category.toLowerCase().includes(articlesSearch.toLowerCase())
  );
  
  const articlesTotalPages = Math.ceil(filteredMyArticles.length / articlesPerPage);
  const articlesStartIndex = (articlesCurrentPage - 1) * articlesPerPage;
  const articlesEndIndex = articlesStartIndex + articlesPerPage;
  const paginatedArticles = filteredMyArticles.slice(articlesStartIndex, articlesEndIndex);

  // 我的收藏检索和分页逻辑
  const filteredMyCollections = myCollections.filter(collection => 
    collection.title.toLowerCase().includes(collectionsSearch.toLowerCase()) ||
    collection.author.toLowerCase().includes(collectionsSearch.toLowerCase()) ||
    collection.category.toLowerCase().includes(collectionsSearch.toLowerCase())
  );
  
  const collectionsTotalPages = Math.ceil(filteredMyCollections.length / collectionsPerPage);
  const collectionsStartIndex = (collectionsCurrentPage - 1) * collectionsPerPage;
  const collectionsEndIndex = collectionsStartIndex + collectionsPerPage;
  const paginatedCollections = filteredMyCollections.slice(collectionsStartIndex, collectionsEndIndex);
  
  // 获取所有标签
  const allTags = Array.from(new Set(articles.flatMap(article => article.tags)));

  // 分页组件
  const Pagination = ({ currentPage, totalPages, onPageChange }: { currentPage: number; totalPages: number; onPageChange: (page: number) => void }) => {
    const pages = [];
    const maxVisiblePages = 5;
    
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    
    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }
    
    return (
      <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
        <div className="text-sm text-gray-500 dark:text-gray-400">
          显示 {((currentPage - 1) * 10) + 1} 至 {Math.min(currentPage * 10, totalPages * 10)} 条，共 {totalPages * 10} 条
        </div>
        <div className="flex space-x-2">
          <button
            onClick={() => onPageChange(currentPage - 1)}
            disabled={currentPage === 1}
            className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i className="fa-solid fa-chevron-left text-xs"></i>
          </button>
          
          {pages.map(page => (
            <button
              key={page}
              onClick={() => onPageChange(page)}
              className={`px-3 py-1 border rounded-md ${
                page === currentPage
                  ? 'border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                  : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600'
              }`}
            >
              {page}
            </button>
          ))}
          
          <button
            onClick={() => onPageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
            className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i className="fa-solid fa-chevron-right text-xs"></i>
          </button>
        </div>
      </div>
    );
  };
  
  // 过滤文章数据
  const filteredArticles = articles.filter(article => {
    const matchesSearch = 
      article.title.toLowerCase().includes(searchTerm.toLowerCase()) || 
      article.excerpt.toLowerCase().includes(searchTerm.toLowerCase()) ||
      article.author.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesCategory = categoryFilter === 'all' || article.category === categoryFilter;
    const matchesStatus = statusFilter === 'all' || article.status === statusFilter;
    
    // 根据当前tab筛选文章
    const matchesTab = activeTab === 'square' || 
                      (activeTab === 'my' && article.author === '当前用户'); // 这里需要根据实际用户信息调整
    
    return matchesSearch && matchesCategory && matchesStatus && matchesTab;
  });
  
  const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      // 搜索逻辑
    }
  };
  
  const handleCreateArticle = () => {
    toast('创建新文章');
  };
  
  const handleViewArticle = (id: number) => {
    // 从所有可能的数据源中查找文章
    const allArticles = [...articles, ...myArticles, ...myCollections];
    const article = allArticles.find(a => a.id === id);
    
    if (article) {
      setSelectedArticle(id);
      setDrawerOpen(true);
    } else {
      toast.error('文章不存在或已被删除');
    }
  };
  
  const handleCloseArticle = () => {
    setSelectedArticle(null);
  };
  
  // 获取当前选中的文章
  const currentArticle = selectedArticle 
    ? [...articles, ...myArticles, ...myCollections].find(article => article.id === selectedArticle) 
    : null;
  
  // 统计数据计算
  const currentTabArticles = articles.filter(article => 
    activeTab === 'square' || (activeTab === 'my' && article.author === '当前用户')
  );
  
  const totalArticles = currentTabArticles.length;
  const totalViews = currentTabArticles.reduce((sum, article) => sum + article.viewCount, 0);
  const totalAuthors = activeTab === 'square' 
    ? Array.from(new Set(articles.map(article => article.author))).length
    : 1; // 我的知识库只有当前用户
  
  // 处理关闭抽屉
  const handleCloseDrawer = () => {
    setDrawerOpen(false);
    setSelectedArticle(null);
  };

  return (
    <div className="h-full">
      <div className="mb-6">
        <motion.div 
          className="mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
        <h1 className="text-2xl font-bold text-gray-800 dark:text-white">知识库</h1>
        <p className="text-gray-600 dark:text-gray-300 mt-1">团队知识共享与沉淀的中心</p>
        </motion.div>
        
        {/* Tab切换 */}
        <div className="mt-4 border-b border-gray-200 dark:border-gray-700">
          <nav className="-mb-px flex space-x-8">
            <button
              onClick={() => setActiveTab('square')}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'square'
                  ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
              }`}
            >
              广场
            </button>
            <button
              onClick={() => setActiveTab('my')}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'my'
                  ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
              }`}
            >
              我的知识库
            </button>
          </nav>
        </div>
      </div>
      
      {/* 文章列表视图 - 始终显示，抽屉会覆盖在上面 */}
      <div className={drawerOpen ? 'opacity-30 pointer-events-none' : ''}>
        <>
          {/* 概览卡片 */}
          <div className="grid grid-cols-4 gap-6 mb-6">
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 hover:shadow-md transition-shadow"
        >
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">
              {activeTab === 'square' ? '总文章数' : '我的文章数'}
            </h3>
            <i className="fa-solid fa-file-lines text-blue-500"></i>
          </div>
          <div className="flex items-end justify-between">
            <p className="text-3xl font-bold text-gray-900 dark:text-gray-100">{totalArticles}</p>
            <p className="text-sm text-green-600 flex items-center">
              <i className="fa-solid fa-arrow-up mr-1"></i>12%
            </p>
          </div>
        </motion.div>
        
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3, delay: 0.1 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 hover:shadow-md transition-shadow"
        >
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">
              {activeTab === 'square' ? '总分类数' : '我的分类数'}
            </h3>
            <i className="fa-solid fa-layer-group text-indigo-500"></i>
          </div>
          <div className="flex items-end justify-between">
            <p className="text-3xl font-bold text-gray-900 dark:text-gray-100">{categoryData.length}</p>
            <p className="text-sm text-green-600 flex items-center">
              <i className="fa-solid fa-arrow-up mr-1"></i>5%
            </p>
          </div>
        </motion.div>
        
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3, delay: 0.2 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 hover:shadow-md transition-shadow"
        >
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">
              {activeTab === 'square' ? '总阅读量' : '我的阅读量'}
            </h3>
            <i className="fa-solid fa-eye text-green-500"></i>
          </div>
          <div className="flex items-end justify-between">
            <p className="text-3xl font-bold text-gray-900 dark:text-gray-100">
              {totalViews}
            </p>
            <p className="text-sm text-green-600 flex items-center">
              <i className="fa-solid fa-arrow-up mr-1"></i>18%
            </p>
          </div>
        </motion.div>
        
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3, delay: 0.3 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 hover:shadow-md transition-shadow"
        >
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">
              {activeTab === 'square' ? '活跃作者' : '我的状态'}
            </h3>
            <i className="fa-solid fa-users text-purple-500"></i>
          </div>
          <div className="flex items-end justify-between">
            <p className="text-3xl font-bold text-gray-900 dark:text-gray-100">
              {totalAuthors}
            </p>
            <p className="text-sm text-green-600 flex items-center">
              <i className="fa-solid fa-arrow-up mr-1"></i>3%
            </p>
          </div>
        </motion.div>
      </div>
          
          {/* 推荐和近期发布区域 - 只在广场显示 */}
      {activeTab === 'square' && (
        <div className="grid grid-cols-2 gap-6 mb-6">
          {/* 推荐文章 */}
          <motion.div 
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.3 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5"
          >
            <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-4">推荐文章</h2>
            <div className="space-y-4">
              {filteredArticles.filter(article => article.isRecommended).slice(0, 3).map((article) => (
                <motion.div 
                  key={article.id} 
                  whileHover={{ scale: 1.02 }}
                  className="cursor-pointer"
                  onClick={() => handleViewArticle(article.id)}
                >
                  <h3 className="text-base font-medium text-gray-800 dark:text-gray-100 mb-1">{article.title}</h3>
                  <p className="text-sm text-gray-600 dark:text-gray-400 mb-2 line-clamp-2">{article.excerpt}</p>
                  <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                    <div className="flex items-center">
                      <UserAvatar name={article.author} />
                      <span className="ml-2">{article.author}</span>
                    </div>
                    <div className="flex items-center">
                      <i className="fa-solid fa-eye mr-1"></i>
                      <span>{article.viewCount > 1000 ? `${(article.viewCount / 1000).toFixed(1)}k` : article.viewCount}</span>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          </motion.div>
          
          {/* 近期发布 */}
          <motion.div 
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.3, delay: 0.1 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5"
          >
            <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-4">近期发布</h2>
            <div className="space-y-4">
              {filteredArticles.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)).slice(0, 3).map((article) => (
                <motion.div 
                  key={article.id} 
                  whileHover={{ scale: 1.02 }}
                  className="cursor-pointer"
                  onClick={() => handleViewArticle(article.id)}
                >
                  <h3 className="text-base font-medium text-gray-800 dark:text-gray-100 mb-1">{article.title}</h3>
                  <p className="text-sm text-gray-600 dark:text-gray-400 mb-2 line-clamp-2">{article.excerpt}</p>
                  <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                    <div className="flex items-center">
                      <UserAvatar name={article.author} />
                      <span className="ml-2">{article.author}</span>
                    </div>
                    <div className="flex items-center">
                      <i className="fa-solid fa-eye mr-1"></i>
                      <span>{article.viewCount > 1000 ? `${(article.viewCount / 1000).toFixed(1)}k` : article.viewCount}</span>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          </motion.div>
        </div>
      )}
          
          {/* 文章列表 - 根据tab显示不同布局 */}
          {activeTab === 'square' ? (
            // 广场标签页：显示优化后的文章列表
            <div className="space-y-4">
              {filteredArticles.map((article) => (
                <motion.div 
                  key={article.id}
                  whileHover={{ y: -3 }}
                  className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 cursor-pointer hover:shadow-md transition-all"
                >
                  <div className="cursor-pointer" onClick={() => handleViewArticle(article.id)}>
                    <div className="flex items-center mb-2">
                      <UserAvatar name={article.author} />
                      <span className="ml-2 text-sm text-gray-600 dark:text-gray-400">{article.author}</span>
                    </div>
                    <h3 className="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-2">{article.title}</h3>
                    <p className="text-gray-600 dark:text-gray-400 mb-3">{article.excerpt}</p>
                    <div className="flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
                      <div className="flex items-center space-x-4">
                        <span className="flex items-center">
                          <i className="fa-solid fa-eye mr-1"></i>
                          {article.viewCount > 1000 ? `${(article.viewCount / 1000).toFixed(1)}k` : article.viewCount}
                        </span>
                        <span className="flex items-center">
                          <i className="fa-solid fa-thumbs-up mr-1"></i>
                          {article.likeCount}
                        </span>
                        <span className="flex items-center">
                          <i className="fa-solid fa-bookmark mr-1"></i>
                          {article.collectCount}
                        </span>
                      </div>
                      <CategoryTag category={article.category} />
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          ) : (
            // 我的知识库标签页：通过子标签切换显示我的文章和我的收藏
            <div className="space-y-6">
              {/* 子标签切换 */}
              <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700">
                <div className="p-5 border-b border-gray-200 dark:border-gray-700">
                  <div className="flex space-x-4">
                    <button
                      onClick={() => setMyTab('articles')}
                      className={`px-4 py-2 rounded-lg font-medium text-sm ${
                        myTab === 'articles'
                          ? 'bg-blue-100 text-blue-600 dark:bg-blue-900 dark:text-blue-400'
                          : 'text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
                      }`}
                    >
                      我的文章
                    </button>
                    <button
                      onClick={() => setMyTab('collections')}
                      className={`px-4 py-2 rounded-lg font-medium text-sm ${
                        myTab === 'collections'
                          ? 'bg-blue-100 text-blue-600 dark:bg-blue-900 dark:text-blue-400'
                          : 'text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
                      }`}
                    >
                      我的收藏
                    </button>
                  </div>
                </div>
                
                {/* 内容区域 */}
                <div className="p-5">
                  {myTab === 'articles' ? (
                    // 我的文章表格
                    <div>
                      <div className="flex justify-between items-center mb-4">
                        <div>
                          <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-100">我的文章</h2>
                          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">管理您创建的所有文章</p>
                        </div>
                        <div className="flex items-center space-x-4">
                          <div className="relative w-64">
                            <input
                              type="text"
                              placeholder="搜索文章标题或分类..."
                              value={articlesSearch}
                              onChange={(e) => {
                                setArticlesSearch(e.target.value);
                                setArticlesCurrentPage(1); // 重置到第一页
                              }}
                              className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            />
                            <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                          </div>
                          <button 
                            className="flex items-center bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
                            onClick={handleCreateArticle}
                          >
                            <i className="fa-solid fa-plus mr-2"></i>
                            新建文章
                          </button>
                        </div>
                      </div>
                      
                      <div className="mb-4 text-sm text-gray-500 dark:text-gray-400">
                        共 {filteredMyArticles.length} 篇文章
                      </div>
                      
                      <div className="overflow-x-auto">
                        <table className="w-full">
                          <thead className="bg-gray-50 dark:bg-gray-700">
                            <tr>
                              <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">标题</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">展现</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">阅读</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">评论</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">点赞</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">收藏</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                            {paginatedArticles.map((article) => (
                              <tr key={article.id} className="hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer" onClick={() => handleViewArticle(article.id)}>
                                <td className="py-3 px-4">
                                  <div className="flex items-center">
                                    <div className="flex-shrink-0 h-10 w-10 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center">
                                      <i className="fa-solid fa-file-lines text-blue-600 dark:text-blue-400"></i>
                                    </div>
                                    <div className="ml-4">
                                      <div className="text-sm font-medium text-gray-900 dark:text-gray-100">{article.title}</div>
                                      <div className="text-xs text-gray-500 dark:text-gray-400">{article.category}</div>
                                    </div>
                                  </div>
                                </td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">
                                  <StatusBadge status={article.status} />
                                </td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">{article.viewCount}</td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">{article.commentCount}</td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">{article.likeCount}</td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">{article.collectCount}</td>
                                <td className="py-3 px-4 text-center text-sm">
                                  <div className="flex justify-center space-x-2">
                                    <button 
                                      className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
                                      onClick={(e) => {
                                        e.stopPropagation();
                                        toast('编辑文章');
                                      }}
                                    >
                                      <i className="fa-solid fa-pen-to-square"></i>
                                    </button>
                                    <button 
                                      className="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300"
                                      onClick={(e) => {
                                        e.stopPropagation();
                                        toast('删除文章');
                                      }}
                                    >
                                      <i className="fa-solid fa-trash"></i>
                                    </button>
                                  </div>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                      
                      {articlesTotalPages > 0 && (
                        <Pagination 
                          currentPage={articlesCurrentPage} 
                          totalPages={articlesTotalPages} 
                          onPageChange={setArticlesCurrentPage} 
                        />
                      )}
                    </div>
                  ) : (
                    // 我的收藏表格
                    <div>
                      <div className="flex justify-between items-center mb-4">
                        <div>
                          <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-100">我的收藏</h2>
                          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">您收藏的所有文章</p>
                        </div>
                        <div className="relative w-64">
                          <input
                            type="text"
                            placeholder="搜索标题、作者或分类..."
                            value={collectionsSearch}
                            onChange={(e) => {
                              setCollectionsSearch(e.target.value);
                              setCollectionsCurrentPage(1); // 重置到第一页
                            }}
                            className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                          />
                          <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        </div>
                      </div>
                      
                      <div className="mb-4 text-sm text-gray-500 dark:text-gray-400">
                        共 {filteredMyCollections.length} 篇收藏文章
                      </div>
                      
                      <div className="overflow-x-auto">
                        <table className="w-full">
                          <thead className="bg-gray-50 dark:bg-gray-700">
                            <tr>
                              <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">标题</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">作者</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">分类</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">阅读</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">点赞</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">收藏</th>
                              <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                            {paginatedCollections.map((article) => (
                              <tr key={article.id} className="hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer" onClick={() => handleViewArticle(article.id)}>
                                <td className="py-3 px-4">
                                  <div className="flex items-center">
                                    <div className="flex-shrink-0 h-10 w-10 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center">
                                      <i className="fa-solid fa-bookmark text-blue-600 dark:text-blue-400"></i>
                                    </div>
                                    <div className="ml-4">
                                      <div className="text-sm font-medium text-gray-900 dark:text-gray-100">{article.title}</div>
                                      <div className="text-xs text-gray-500 dark:text-gray-400">{article.summary}</div>
                                    </div>
                                  </div>
                                </td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">{article.author}</td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">
                                  <CategoryTag category={article.category} />
                                </td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">{article.viewCount}</td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">{article.likeCount}</td>
                                <td className="py-3 px-4 text-center text-sm text-gray-900 dark:text-gray-100">{article.collectCount}</td>
                                <td className="py-3 px-4 text-center text-sm">
                                  <div className="flex justify-center space-x-2">
                                    <button 
                                      className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
                                      onClick={(e) => {
                                        e.stopPropagation();
                                        toast('查看文章');
                                      }}
                                    >
                                      <i className="fa-solid fa-eye"></i>
                                    </button>
                                    <button 
                                      className="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300"
                                      onClick={(e) => {
                                        e.stopPropagation();
                                        toast('取消收藏');
                                      }}
                                    >
                                      <i className="fa-solid fa-bookmark-slash"></i>
                                    </button>
                                  </div>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                      
                      {collectionsTotalPages > 0 && (
                        <Pagination 
                          currentPage={collectionsCurrentPage} 
                          totalPages={collectionsTotalPages} 
                          onPageChange={setCollectionsCurrentPage} 
                        />
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </>
      </div>

      {/* 抽屉式文章详情 */}
      {drawerOpen && currentArticle && (
        <Drawer
          isOpen={drawerOpen}
          onClose={handleCloseDrawer}
          title={currentArticle.title}
          className="w-[80vw] max-w-none"
        >
          <div className="bg-white dark:bg-gray-800">
            {/* 文章详情导航栏 */}
            <div className="sticky top-0 z-10 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 p-4">
              <div className="flex justify-between items-center">
                <button 
                  className="flex items-center text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
                  onClick={handleCloseDrawer}
                >
                  <i className="fa-solid fa-arrow-left mr-1"></i>
                  返回列表
                </button>
                <div className="flex items-center space-x-4">
                  <div className="flex space-x-2">
                    <button className="flex items-center text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-300">
                      <i className="fa-solid fa-pen-to-square mr-1"></i>
                      编辑
                    </button>
                    <button className="flex items-center text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-300">
                      <i className="fa-solid fa-share-nodes mr-1"></i>
                      分享
                    </button>
                  </div>
                  
                  {/* 文章操作按钮 */}
                  <div className="flex items-center space-x-2 border-l border-gray-200 dark:border-gray-700 pl-4">
                    <button 
                      className="flex items-center text-gray-600 hover:text-red-600 dark:text-gray-400 dark:hover:text-red-400"
                      onClick={() => {
                        if (currentArticle) {
                          const updatedArticle = {...currentArticle, likeCount: (currentArticle.likeCount || 0) + 1};
                          // 这里应该调用API更新点赞状态
                          toast('点赞成功');
                        }
                      }}
                    >
                      <i className="fa-solid fa-thumbs-up mr-1"></i>
                      点赞 ({currentArticle?.likeCount || 0})
                    </button>
                    <button 
                      className="flex items-center text-gray-600 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400"
                      onClick={() => {
                        if (currentArticle) {
                          const updatedArticle = {...currentArticle, collectCount: (currentArticle.collectCount || 0) + 1};
                          // 这里应该调用API更新收藏状态
                          toast('收藏成功');
                        }
                      }}
                    >
                      <i className="fa-solid fa-bookmark mr-1"></i>
                      收藏 ({currentArticle?.collectCount || 0})
                    </button>
                  </div>
                </div>
              </div>
              
              {/* 文章标题导航 */}
              <div className="mt-3 flex items-center justify-between sticky top-0 bg-white dark:bg-gray-800 py-3 z-10">
                <h1 className="text-xl font-bold text-gray-800 dark:text-gray-100 truncate">{currentArticle?.title || ''}</h1>
                <div className="flex items-center space-x-4 text-sm text-gray-500 dark:text-gray-400">
                  <div className="flex items-center">
                    <UserAvatar name={currentArticle?.author || ''} size="sm" />
                    <span className="ml-2">{currentArticle?.author || ''}</span>
                  </div>
                  <span>•</span>
                  <span>阅读 {currentArticle?.viewCount || 0} 次</span>
                  <span>•</span>
                  <span>评论 {currentArticle?.commentCount || 0}</span>
                  <span>•</span>
                  <span>点赞 {currentArticle?.likeCount || 0}</span>
                  <span>•</span>
                  <span>收藏 {currentArticle?.collectCount || 0}</span>
                </div>
              </div>
            </div>
            
            <div className="p-5">
              
              {/* 文章元信息 */}
              <div className="border-b border-gray-200 dark:border-gray-700 pb-5 mb-5">
                <div className="flex items-center justify-between mb-4">
                  <StatusBadge status={currentArticle?.status || 'draft'} />
                  <CategoryTag category={currentArticle?.category || 'general'} />
                </div>
                <div className="flex flex-wrap gap-2">
                  {currentArticle?.tags?.map((tag) => (
                    <Tag key={tag} text={tag} />
                  )) || []}
                </div>
              </div>
              
              {/* 文章内容与左侧导航 */}
              <div className="flex gap-8">
                {/* 左侧导航栏 */}
                <div className="w-64 flex-shrink-0">
                  <div className="sticky top-24">
                    <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                      <h3 className="font-semibold text-gray-800 dark:text-gray-200 mb-3">文章导航</h3>
                      <nav className="space-y-2">
                        <a href="#introduction" className="block text-sm text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
                          • 背景介绍
                        </a>
                        <a href="#concepts" className="block text-sm text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
                          • 核心概念
                        </a>
                        <a href="#practice" className="block text-sm text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
                          • 实践指南
                        </a>
                        <a href="#faq" className="block text-sm text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
                          • 常见问题
                        </a>
                        <a href="#summary" className="block text-sm text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
                          • 总结与展望
                        </a>
                      </nav>
                    </div>
                  </div>
                </div>
                
                {/* 文章内容 */}
                <div className="flex-1 prose max-w-none">
                  <p className="text-lg text-gray-700 dark:text-gray-300 mb-6">{currentArticle?.excerpt || ''}</p>
                  
                  <section id="introduction" className="scroll-mt-20">
                    <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-100 mt-8 mb-4">背景介绍</h2>
                    <p className="text-gray-700 dark:text-gray-300 mb-4">
                      本文详细介绍了相关主题的最佳实践和经验总结，帮助团队成员更好地理解和应用相关技术。
                    </p>
                    <p className="text-gray-700 dark:text-gray-300">
                      为什么这个主题很重要，解决了什么问题，以及在实际项目中的应用价值。
                    </p>
                  </section>
                  
                  <section id="concepts" className="scroll-mt-20">
                    <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-100 mt-8 mb-4">核心概念</h2>
                    <p className="text-gray-700 dark:text-gray-300 mb-4">
                      相关技术或方法的基本原理和关键术语，帮助读者建立完整的知识体系。
                    </p>
                    <ul className="text-gray-700 dark:text-gray-300 space-y-2">
                      <li>• 关键技术原理</li>
                      <li>• 核心术语定义</li>
                      <li>• 技术架构概述</li>
                    </ul>
                  </section>
                  
                  <section id="practice" className="scroll-mt-20">
                    <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-100 mt-8 mb-4">实践指南</h2>
                    <p className="text-gray-700 dark:text-gray-300 mb-4">
                      具体的实施步骤和注意事项，包含详细的配置示例和代码片段。
                    </p>
                    <pre className="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg overflow-x-auto mt-4">
                      <code className="text-sm text-gray-800 dark:text-gray-200">
                        {`// 示例代码
function exampleFunction() {
  const result = doSomething();
  return result;
}`}
                      </code>
                    </pre>
                  </section>
                  
                  <section id="faq" className="scroll-mt-20">
                    <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-100 mt-8 mb-4">常见问题</h2>
                    <p className="text-gray-700 dark:text-gray-300 mb-4">
                      在实践过程中可能遇到的问题及解决方案，帮助读者避免常见陷阱。
                    </p>
                    <div className="space-y-3">
                      <div className="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                        <h3 className="font-semibold text-gray-800 dark:text-gray-200">Q: 常见问题1？</h3>
                        <p className="text-gray-700 dark:text-gray-300 mt-2">A: 详细解答和解决方案。</p>
                      </div>
                      <div className="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                        <h3 className="font-semibold text-gray-800 dark:text-gray-200">Q: 常见问题2？</h3>
                        <p className="text-gray-700 dark:text-gray-300 mt-2">A: 详细解答和解决方案。</p>
                      </div>
                    </div>
                  </section>
                  
                  <section id="summary" className="scroll-mt-20">
                    <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-100 mt-8 mb-4">总结与展望</h2>
                    <p className="text-gray-700 dark:text-gray-300">
                      通过本文的学习，团队成员应该能够更好地理解和应用相关技术，提高工作效率和质量。
                      同时展望未来技术发展趋势和可能的改进方向。
                    </p>
                  </section>
                </div>
              </div>
              
              {/* 评论区域 */}
              <div className="mt-8 border-t border-gray-200 dark:border-gray-700 pt-8">
                <div className="flex justify-between items-center mb-6">
                  <h3 className="text-xl font-bold text-gray-800 dark:text-gray-100">评论 ({currentArticle?.commentCount || 0})</h3>
                  <button className="flex items-center text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                    <i className="fa-solid fa-sort mr-1"></i>
                    最新
                  </button>
                </div>
                
                {/* 评论输入框 */}
                <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 mb-6">
                  <textarea 
                    placeholder="写下你的评论..."
                    className="w-full h-20 p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                  />
                  <div className="flex justify-between items-center mt-3">
                    <div className="flex items-center space-x-2 text-sm text-gray-500 dark:text-gray-400">
                      <button className="hover:text-blue-600 dark:hover:text-blue-400">
                        <i className="fa-solid fa-face-smile"></i>
                      </button>
                      <button className="hover:text-blue-600 dark:hover:text-blue-400">
                        <i className="fa-solid fa-at"></i>
                      </button>
                    </div>
                    <button className="bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors">
                      发表评论
                    </button>
                  </div>
                </div>
                
                {/* 评论列表 */}
                <div className="space-y-4">
                  <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
                    <div className="flex items-start space-x-3">
                      <UserAvatar name="评论者A" />
                      <div className="flex-1">
                        <div className="flex justify-between items-start">
                          <div>
                            <span className="font-medium text-gray-800 dark:text-gray-200">评论者A</span>
                            <span className="text-xs text-gray-500 dark:text-gray-400 ml-2">2小时前</span>
                          </div>
                          <button className="text-gray-400 hover:text-red-500">
                            <i className="fa-solid fa-heart"></i>
                          </button>
                        </div>
                        <p className="text-gray-700 dark:text-gray-300 mt-2">
                          这篇文章写得非常好，对我帮助很大！
                        </p>
                        <div className="flex items-center space-x-4 mt-3 text-sm text-gray-500 dark:text-gray-400">
                          <button className="hover:text-blue-600 dark:hover:text-blue-400">
                            回复
                          </button>
                          <button className="hover:text-red-600 dark:hover:text-red-400">
                            <i className="fa-solid fa-thumbs-up mr-1"></i>12
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
                    <div className="flex items-start space-x-3">
                      <UserAvatar name="评论者B" />
                      <div className="flex-1">
                        <div className="flex justify-between items-start">
                          <div>
                            <span className="font-medium text-gray-800 dark:text-gray-200">评论者B</span>
                            <span className="text-xs text-gray-500 dark:text-gray-400 ml-2">1天前</span>
                          </div>
                          <button className="text-red-500">
                            <i className="fa-solid fa-heart"></i>
                          </button>
                        </div>
                        <p className="text-gray-700 dark:text-gray-300 mt-2">
                          实践指南部分很实用，期待更多这样的内容！
                        </p>
                        <div className="flex items-center space-x-4 mt-3 text-sm text-gray-500 dark:text-gray-400">
                          <button className="hover:text-blue-600 dark:hover:text-blue-400">
                            回复
                          </button>
                          <button className="hover:text-red-600 dark:hover:text-red-400">
                            <i className="fa-solid fa-thumbs-up mr-1"></i>8
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Drawer>
      )}
    </div>
  );
}